<template>
  <div ref="container" class="topology-container"></div>
</template>

<script>
import { Graph } from '@antv/g6'

export default {
  name: 'TopologyMap',
  props: {
    topology: {
      type: [Array, Object],
      required: true
    }
  },
  data() {
    return {
      graph: null
    }
  },
  mounted() {
    this.initGraph()
  },
  methods: {
    initGraph() {
      const container = this.$refs.container

      const graph = new Graph({
        container,
        width: container.scrollWidth,
        height: container.scrollHeight,
        modes: {
          default: ['drag-canvas', 'zoom-canvas', 'drag-node']
        },
        layout: {
          type: 'dagre',
          rankdir: 'TB',
          nodesep: 50,
          ranksep: 70
        },
        defaultNode: {
          type: 'rect',
          size: [120, 40],
          style: {
            radius: 8,
            fill: '#fff',
            stroke: '#3498db',
            lineWidth: 2,
            shadowColor: '#999',
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowOffsetY: 5
          }
        },
        defaultEdge: {
          type: 'polyline',
          style: {
            stroke: '#91d5ff',
            lineWidth: 2,
            endArrow: false
          }
        }
      })

      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        if (graph) {
          graph.changeSize(
            container.scrollWidth,
            container.scrollHeight
          )
        }
      })

      this.updateData(graph)
    },
    updateData(graph) {
      if (!graph) return

      // 转换数据格式
      const data = this.convertToG6Data(this.topology)
      graph.data(data)
      graph.render()
    },
    convertToG6Data(source) {
      const nodes = []
      const edges = []

      const traverse = (node, parent) => {
        nodes.push({
          id: node.id,
          label: node.label
        })

        if (parent) {
          edges.push({
            source: parent.id,
            target: node.id
          })
        }

        if (node.children) {
          node.children.forEach(child => traverse(child, node))
        }
      }

      traverse(Array.isArray(source) ? source[0] : source)

      return {
        nodes,
        edges
      }
    }
  },
}
</script>

<style scoped>
.topology-container {
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom right, #f8f9fa, #e9ecef);
}
</style>
